package com.ruoyi.system.service.impl;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.IOUtil;
import com.ruoyi.common.utils.StrKit;
import com.ruoyi.system.domain.Device;
import com.ruoyi.system.domain.ListDetail;
import com.ruoyi.system.domain.StockLog;
import com.ruoyi.system.mapper.ListDetailMapper;
import com.ruoyi.system.mapper.StockLogMapper;
import com.ruoyi.system.mapper.SupplierMapper;
import com.ruoyi.system.service.IDeviceService;
import com.ruoyi.system.service.IStockLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.OrderListMapper;
import com.ruoyi.system.domain.OrderList;
import com.ruoyi.system.service.IOrderListService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 采购单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-15
 */
@Service
public class OrderListServiceImpl implements IOrderListService 
{
    @Autowired
    private OrderListMapper orderListMapper;
    @Autowired
    private ListDetailMapper listDetailMapper;
    @Autowired
    private IStockLogService stockLogService;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private IDeviceService deviceService;
    @Value("${ruoyi.imgBaseUrl}")
    String imgBaseUrl ;

    /**
     * 批量支付订单
     *
     * @param ids
     * @return
     */
    @Override
    public AjaxResult checkoutOrder(String ids) {

        int res =orderListMapper.checkoutOrder(ids);
        return AjaxResult.success(res);
    }

    /**
     * 查询采购单详情
     *
     * @param id
     * @return
     */
    @Override
    public ListDetail selectListDetailById(Long id) {
        return listDetailMapper.selectListDetailById(id);
    }

    /**
     * 核验订单
     *
     * @param detailList
     * @return
     */
    @Override
    public AjaxResult checkOrder(List<ListDetail> detailList,SysUser user) {

        for (ListDetail detail : detailList) {
            //更新详单信息
            listDetailMapper.updateListDetail(detail);
            //判断如果有退货，则操作库存
            if(detail.getRefundNum()!=null&&detail.getRefundNum()>0) {
                //操作库存
                StockLog stockLog = new StockLog();
                stockLog.setGoodsid(detail.getGoodsid());
                stockLog.setShopId(user.getShopId());
                stockLog.setShopName(user.getShopName());
                stockLog.setGoodsNum(detail.getRefundNum());
                stockLog.setCompanyId(user.getCompanyId());
                stockLog.setCompanyName(user.getCompanyName());
                stockLog.setRemark("检验不合格退货，采购单号:" + detail.getListid());
                stockLog.setGoodsName(detail.getGoodsName());
                stockLog.setInOut("2");
                stockLog.setListid(detail.getListid());
                stockLog.setType("6");
                stockLogService.insertStockLog(stockLog);
            }

        }


        //更新订单状态
        orderListMapper.updateOrderListStatus4();
        return AjaxResult.success();
    }

    /**
     * 电子秤入库
     * @param detailList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deviceStockIn(List<ListDetail> detailList, Device device) {
        for (ListDetail detail : detailList) {
            //更新LISTDETAIL
            listDetailMapper.updateListDetail(detail);
            //操作库存
            StockLog stockLog = new StockLog();
            stockLog.setGoodsid(detail.getGoodsid());
            stockLog.setShopId(device.getShopId());
            stockLog.setShopName(device.getShopName());
            stockLog.setGoodsNum(detail.getGoodsNumReal());
            stockLog.setCompanyId(device.getCompanyId());
            stockLog.setCompanyName(device.getCompanyName());
            stockLog.setRemark("电子秤称重入库，采购单号:"+detail.getListid());
            stockLog.setGoodsName(detail.getGoodsName());
            stockLog.setInOut("1");
            stockLog.setListid(detail.getListid());
            stockLog.setType("1");
            stockLogService.insertStockLog(stockLog);
        }
        //更新订单状态
        orderListMapper.updateOrderListStatus31();
        //更新设备最后使用时间
        device.setLasttime(IOUtil.getdate("yyyy-MM-dd HH:mm:ss"));
        deviceService.updateDevice(device);

        return AjaxResult.success();
    }

    /**
     * 评价订单
     *
     * @param data
     * @return
     */
    @Override
    public AjaxResult evaluate(OrderList data) {
        long orderId = data.getId();
        //查询订单信息，判断状态
        OrderList orderList = orderListMapper.selectOrderListById(orderId);
        if(!orderList.getStatus().equals("4"))return AjaxResult.error("订单状态有误");
        //更新订单信息
        orderList.setStatus("5");
        orderList.setStarService(data.getStarService());
        orderList.setStarQuality(data.getStarQuality());
        orderList.setStarTimely(data.getStarTimely());

        int result = orderListMapper.updateOrderList(orderList);
        if(result>0){
            //更新供货商整体评价信息
            supplierMapper.recomputeStar(orderList.getSupplyId());
        }
        return AjaxResult.success(result);
    }

    /**
     * 确认收货订单
     *
     * @param jsonObject
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult receiveOrder(JSONObject jsonObject) {
        long orderId = jsonObject.getLong("id");
        //查询订单信息，判断状态
        OrderList orderList = orderListMapper.selectOrderListById(orderId);
        if(!orderList.getStatus().equals("3"))return AjaxResult.error("订单状态有误");
        //商品信息
        JSONArray jsonArray = jsonObject.getJSONArray("goods");
        List<ListDetail> listDetails = JSONArray.parseArray(jsonArray.toJSONString(), ListDetail.class);
        //更新商品信息
        double realTotalPrice = 0;//真实总价
        for (ListDetail listDetail : listDetails) {

            //更新订单商品信息
            listDetail.setGoodsNumReal(listDetail.getGoodsNumReal());
            double totalPrice = listDetail.getRealPrice()*listDetail.getGoodsNumReal();
            listDetail.setTotalPriceReal(totalPrice);
            realTotalPrice += totalPrice;
            listDetailMapper.updateListDetail(listDetail);


            //操作库存
            StockLog stockLog = new StockLog();
            stockLog.setGoodsid(listDetail.getGoodsid());
            stockLog.setShopId(orderList.getShopId());
            stockLog.setShopName(orderList.getShopName());
            stockLog.setGoodsNum(listDetail.getGoodsNumReal());
            stockLog.setGoodsPrice(listDetail.getRealPrice());
            stockLog.setCompanyId(orderList.getCompanyId());
            stockLog.setCompanyName(orderList.getCompanyName());
            stockLog.setCreateTime(listDetail.getCreateTime());
            stockLog.setRemark("采购单收货入库，收货单号:"+orderList.getId());
            stockLog.setGoodsName(listDetail.getGoodsName());
            stockLog.setGoodsNum(listDetail.getGoodsNumReal());
            stockLog.setInOut("1");
            stockLog.setListid(listDetail.getListid());
            stockLog.setType("1");
            stockLogService.insertStockLog(stockLog);
        }


        //更新订单状态
        orderList.setStatus("4");
        orderList.setPrice(realTotalPrice);
        orderList.setArriveTime(IOUtil.getdate("yyyy-MM-dd HH:mm:ss"));
        orderListMapper.updateOrderList(orderList);


        return AjaxResult.success();
    }

    /**
     * 修改订单商品
     *
     * @param jsonObject
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateOrderGoods(JSONObject jsonObject) {
        long listid = jsonObject.getLong("listid");
        //查询订单信息，判断状态
        OrderList orderList = orderListMapper.selectOrderListById(listid);
        if(orderList.getStatus().equals("3")||orderList.getStatus().equals("4"))return AjaxResult.error("订单已确认，不能修改");

        JSONArray goodsArr = jsonObject.getJSONArray("goods");
        List<ListDetail> listDetails = JSONArray.parseArray(goodsArr.toJSONString(), ListDetail.class);
        //查询原有商品信息
        ListDetail ld = new ListDetail();
        ld.setListid(listid);
        List<ListDetail> oldListDetails = listDetailMapper.selectListDetailList(ld);
        //对比原有商品信息，删除无效商品
        for (ListDetail oldListDetail : oldListDetails) {
            boolean flag = false;
            for (ListDetail listDetail : listDetails) {
                if(oldListDetail.getId().equals(listDetail.getId())){
                    flag = true;
                    break;
                }
            }
            if(!flag){
                listDetailMapper.deleteListDetailById(oldListDetail.getId());
            }
        }
        //重新计算总价格
        double totalPrice = 0;
        int kind = 0;
        //更新订单商品信息
        for (ListDetail listDetail : listDetails) {
            //判断如果有id,则为更新操作
            if(listDetail.getId()!=null){
                listDetailMapper.updateListDetail(listDetail);
            }else{
                listDetail.setListid(listid);
                listDetailMapper.insertListDetail(listDetail);
            }
            kind++;
            if(listDetail.getPrice()!=null)totalPrice += listDetail.getTotalPrice();
        }
        //更新订单信息
        if(totalPrice!=0){
            orderList.setKind(kind);
            orderList.setPrice(totalPrice);
            int result = orderListMapper.updateOrderList(orderList);
        }
        return AjaxResult.success();
    }

    /**
     * 根据订单ID，查询商品详情
     *
     * @param id
     * @return
     */
    @Override
    public List<ListDetail> getListGoods(Long id) {
        ListDetail detail = new ListDetail();
        detail.setListid(id);
        List<ListDetail> data = listDetailMapper.selectListDetailList(detail);

        if(data!=null&&data.size()>0){
            for (ListDetail listDetail : data) {
                listDetail.setImageUrl(imgBaseUrl+listDetail.getImageUrl());
                listDetail.setGoodsUnitStr(DictUtils.getDictLabel("sys_goods_unit", listDetail.getGoodsUnit()));
            }
        }

        return data;
    }

    /**
     * 查询采购单
     * 
     * @param id 采购单主键
     * @return 采购单
     */
    @Override
    public OrderList selectOrderListById(Long id)
    {
        return orderListMapper.selectOrderListById(id);
    }

    /**
     * 查询采购单列表
     * 
     * @param orderList 采购单
     * @return 采购单
     */
    @Override
    public List<OrderList> selectOrderListList(OrderList orderList)
    {
        Map params = orderList.getParams();
        if(params!=null){
            for(Object key:params.keySet()){
                System.out.println(key+":"+params.get(key));
            }
        }
        return orderListMapper.selectOrderListList(orderList);
    }

    /**
     * 供应商接单+添加备注
     *
     * @param jsonObject
     */
    @Override
    public AjaxResult takeOrder(JSONObject jsonObject) {
        long listid = jsonObject.getLong("listid");
        //查询订单信息，判断状态
        OrderList orderList = orderListMapper.selectOrderListById(listid);
        if(orderList.getStatus().equals("3")||orderList.getStatus().equals("4"))return AjaxResult.error("订单已确认，不能修改");

        JSONArray goodsArr = jsonObject.getJSONArray("goods");
        List<ListDetail> listDetails = JSONArray.parseArray(goodsArr.toJSONString(), ListDetail.class);

        //更新订单商品信息
        for (ListDetail listDetail : listDetails) {
            listDetailMapper.updateListDetail(listDetail);
        }
        //更新订单信息
        orderList.setStatus("2");
        orderList.setTakeTime(IOUtil.getdate("yyyy-MM-dd HH:mm:ss"));
        int result = orderListMapper.updateOrderList(orderList);
        return AjaxResult.success();
    }

    /**
     * 新增采购单
     * 
     * @param data 采购单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOrderList(JSONObject data)
    {
        System.out.println("采购信息："+data.toString());
        //采购单信息
        OrderList orderList = JSON.parseObject(JSON.toJSONString(data), OrderList.class);
        //补齐信息
        if(StrKit.isBlank(orderList.getOrderNo()))orderList.setOrderNo("CG"+IOUtil.getId(4));
        orderList.setDay(IOUtil.getdate("yyyy-MM-dd"));
        //详情信息
        JSONArray goodsArr = data.getJSONArray("goods");
        List<ListDetail> listDetails = JSONArray.parseArray(goodsArr.toJSONString(), ListDetail.class);

        //插入采购单信息
        orderList.setKind(goodsArr.size());
        int result = orderListMapper.insertOrderList(orderList);
        if(result==0)return 0;
        //处理信息
        double totalPrice = 0;//总价格
        for (ListDetail listDetail : listDetails) {
            listDetail.setListid(orderList.getId());
            listDetail.setGoodsNumReal(listDetail.getGoodsNum());
            listDetail.setRealPrice(listDetail.getPrice());
            listDetail.setTotalPriceReal(listDetail.getTotalPrice());
        }

        //插入采购单
        result =orderListMapper.insertListDetailMulity(listDetails);

        return result;
    }

    /**
     * 修改采购单
     * 
     * @param orderList 采购单
     * @return 结果
     */
    @Override
    public int updateOrderList(OrderList orderList)
    {
        return orderListMapper.updateOrderList(orderList);
    }

    /**
     * 批量删除采购单
     * 
     * @param ids 需要删除的采购单主键
     * @return 结果
     */
    @Override
    public int deleteOrderListByIds(Long[] ids)
    {
        return orderListMapper.deleteOrderListByIds(ids);
    }

    /**
     * 删除采购单信息
     * 
     * @param id 采购单主键
     * @return 结果
     */
    @Override
    public int deleteOrderListById(Long id)
    {
        return orderListMapper.deleteOrderListById(id);
    }

    /**
     * 查询待出库商品
     *
     * @param listDetail
     * @return
     */
    @Override
    public List<ListDetail> getListGoods(ListDetail listDetail) {

        List<ListDetail> listDetails = listDetailMapper.selectListDetailList(listDetail);
        for (ListDetail detail : listDetails) {
            detail.setImageUrl(imgBaseUrl+detail.getImageUrl());
            detail.setGoodsUnitStr(DictUtils.getDictLabel("sys_goods_unit", detail.getGoodsUnit()));
        }

        return listDetails;
    }
}
